<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="down">点我下载</button>
    <div id="dibb"></div>
  </body>
  <script>
    const fileUrl =
      "https://storage.nuonuo.com/linkDownload/-kCqofw2g2mBAouQ1oeNieYtxJUCEo_lJG7_361DBHJTzhBbvAI-A7VllW0H45z1II9efcPg--UERsoqaqRpRw.xml";
    const fileName = "我是文件名.xml";

    //通过a标签下载文件
    function commonalink(blob, fileName) {
      const href = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = href;
      document.body.appendChild(a);
      a.download = fileName;
      a.click(); // 模拟在按钮上的一次鼠标单击
      a.remove();
      URL.revokeObjectURL(a.href); // 释放URL 对象
    }

    // url转换成文件流下载，可以解决下载保存文件名设置不成功的问题，但文件资源过大时速度很慢
    function downloadUrlToBlob(fileUrl, filename) {
      // 通过文件url获取文件流blob
      getFileStream(fileUrl).then((res) => {
        commonalink(res, fileName);
      });
    }

    //获取文件流
    const getFileStream = (url) => {
      return new Promise((resolve, reject) => {
        // 通过请求获取文件blob格式
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = function () {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(this.status);
          }
        };
        xhr.send();
      });
    };

    downloadUrlToBlob(fileUrl, fileName);
  </script>
</html>
